<template>
  <el-config-provider :locale="appStore.locale" :size="(appStore.size as any)">
    <div class="p-5">
      <!-- 查询条件 -->
      <div class="query-condition flex justify-between">
        <div class="condition flex-1 flex flex-wrap">
          <div v-for="item in searchFields" :key="item.id" class="mr-5 mb-3 search-list">
            <span class="text-gray5 text-sm">{{ item.fieldName }}：</span>

            <div class="number-type" v-if="item.fieldType === '数字类型'">
              <el-input-number
                :controls="false"
                placeholder="起"
                v-model="searchInfo.paramMap[item.fieldEname].start"
              ></el-input-number>
              <span class="text-gray mx-2">-</span>
              <el-input-number
                :controls="false"
                placeholder="止"
                v-model="searchInfo.paramMap[item.fieldEname].end"
              ></el-input-number>
            </div>
            <div v-else-if="item.fieldType === '系统人员单选'">
              <el-select
                v-if="orgInfo"
                clearable
                filterable
                class="w-full"
                v-model="searchInfo.paramMap[item.fieldEname]"
              >
                <el-option
                  v-for="item_ in userList"
                  :key="item_.userId"
                  :label="item_.userName"
                  :value="item_.userName"
                ></el-option>
              </el-select>
            </div>
            <div v-else-if="item.fieldType === '系统人员多选'">
              <el-select
                v-if="orgInfo"
                clearable
                collapse-tags
                collapse-tags-tooltip
                multiple
                filterable
                class="w-full"
                v-model="searchInfo.paramMap[item.fieldEname]"
              >
                <el-option
                  v-for="item_ in userList"
                  :key="item_.userId"
                  :label="item_.userName"
                  :value="item_.userName"
                ></el-option>
              </el-select>
            </div>
            <div v-else-if="item.fieldType === '组织名称单选'">
              <el-select
                v-if="orgInfo"
                clearable
                filterable
                class="w-full"
                v-model="searchInfo.paramMap[item.fieldEname]"
              >
                <el-option
                  v-for="item_ in orgInfo"
                  :key="item_.orgId"
                  :label="item_.orgName"
                  :value="item_.orgName"
                ></el-option>
              </el-select>
            </div>
            <div v-else-if="item.fieldType === '组织名称多选'">
              <el-select
                :disabled="judgeEditDisabled(item)"
                v-if="orgInfo"
                clearable
                collapse-tags
                collapse-tags-tooltip
                multiple
                filterable
                class="w-full"
                v-model="searchInfo.paramMap[item.fieldEname]"
              >
                <el-option
                  v-for="item_ in orgInfo"
                  :key="item_.orgId"
                  :label="item_.orgName"
                  :value="item_.orgName"
                ></el-option>
              </el-select>
            </div>
            <div v-else-if="item.fieldType === '审核状态'">
              <el-select v-model="searchInfo.paramMap[item.fieldEname]" placeholder="请选择">
                <el-option label="审核中" value="审核中"></el-option>
                <el-option label="已驳回" value="已驳回"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
              </el-select>
            </div>
            <div v-else-if="item.fieldType === '流转状态'">
              <el-select v-model="searchInfo.paramMap[item.fieldEname]" placeholder="请选择">
                <el-option label="流转中" value="流转中"></el-option>
                <el-option label="已流转" value="已流转"></el-option>
              </el-select>
            </div>
            <div v-else-if="item.fieldType === '复选框'">
              <el-checkbox-group v-model="searchInfo.paramMap[item.fieldEname]">
                <el-checkbox
                  v-for="item_ in queryRealDataArr(item)"
                  :key="item_.id"
                  :label="item_.selectCode"
                >
                  {{ item_.selectName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-else-if="item.fieldType === '日期选择'">
              <el-date-picker
                clearable
                v-model="searchInfo.paramMap[item.fieldEname]"
                type="datetimerange"
                placeholder="请选择"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
            <div v-else-if="item.fieldType === '下拉框'">
              <el-tree-select
                filterable
                :data="queryRealDataArr(item)"
                clearable
                :check-strictly="queryRealDataArrStrict(item)"
                :render-after-expand="false"
                class="w-full"
                v-model="searchInfo.paramMap[item.fieldEname]"
                placeholder="请选择"
                node-key="selectCode"
                :props="{
                  label: 'selectName',
                  children: 'children'
                }"
              />
            </div>
            <div v-else-if="item.fieldType === '省市区'">
              <el-cascader
                class="w-full"
                v-model="searchInfo.paramMap[item.fieldEname]"
                :options="regionData"
                placeholder="请选择省市区"
                filterable
                clearable
              ></el-cascader>
            </div>
            <div v-else-if="item.fieldType === '单选框'">
              <el-radio-group v-model="searchInfo.paramMap[item.fieldEname]">
                <el-radio
                  v-for="item_ in queryRealDataArr(item)"
                  :key="item_.id"
                  :label="item_.selectCode"
                  size="large"
                >
                  {{ item_.selectName }}
                </el-radio>
              </el-radio-group>
            </div>
            <div v-else>
              <el-input
                v-model="searchInfo.paramMap[item.fieldEname]"
                :placeholder="item.fieldName"
              ></el-input>
            </div>
          </div>
          <el-button @click="resetTableData" class="mb-3" type="primary" plain>
            <i-ep-Refresh />
          </el-button>
          <el-button @click="queryTableData" class="mb-3" type="primary">
            <i-ep-Search />
          </el-button>
        </div>
        <div class="button ml-2">
          <el-button
            v-if="functionMap.import.show"
            plain
            type="primary"
            @click="(loadingBtn = false), (showDialog = true)"
          >
            <i-ep-Upload class="mr-1" />
            导入
          </el-button>
          <el-button @click="exportTable" v-if="functionMap.export.show" plain type="primary">
            <i-ep-Download class="mr-1" />
            导出
          </el-button>
          <el-button v-if="functionMap.add.show" plain type="primary" @click="addTableData">
            <i-ep-CirclePlusFilled class="mr-1" />
            新增
          </el-button>
          <el-button type="primary" @click="fieldCustom">
            <i-ep-Tools class="mr-1" />
            列表自定义
          </el-button>
        </div>
      </div>

      <!-- 表格展示 -->
      <div class="table-content mt-2">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          show-summary
          :summary-method="getSummaries"
          :cell-style="cellStyle"
          style="width: 100%"
        >
          <el-table-column
            :fixed="true"
            align="center"
            type="index"
            width="60"
            label="序号"
          ></el-table-column>
          <template v-for="item in fieldList" :key="item.id">
            <el-table-column
              show-overflow-tooltip
              align="center"
              :prop="item.fieldEname"
              :label="item.fieldName"
              v-if="item.show"
              :fixed="item.fixed"
            >
              <template #default="{ row }">
                <span
                  v-if="
                    item.fieldEname &&
                    item.fieldType === '省市区' &&
                    row &&
                    JSON.stringify(row) !== '{}' &&
                    row[item.fieldEname] &&
                    row[item.fieldEname] !== '-'
                  "
                >
                  {{ getRealDataArea(row, item) }}
                </span>
                <span
                  v-else-if="
                    item.fieldEname &&
                    item.fieldType === '下拉框' &&
                    row &&
                    JSON.stringify(row) !== '{}' &&
                    row[item.fieldEname] &&
                    row[item.fieldEname] !== '-'
                  "
                >
                  {{ getRealDataSelect(row, item) }}
                </span>
                <span
                  v-else-if="
                    item.fieldEname &&
                    item.fieldType === '单选框' &&
                    row &&
                    JSON.stringify(row) !== '{}' &&
                    row[item.fieldEname] &&
                    row[item.fieldEname] !== '-'
                  "
                >
                  {{ getRealDataRadio(row, item) }}
                </span>
                <span
                  v-else-if="
                    item.fieldEname &&
                    item.fieldType === '复选框' &&
                    row &&
                    JSON.stringify(row) !== '{}' &&
                    row[item.fieldEname] &&
                    row[item.fieldEname] !== '-'
                  "
                >
                  {{ getRealDataCheck(row, item) }}
                </span>
                <span
                  v-else-if="
                    item.fieldEname &&
                    item.fieldType === '文件上传-最多五个' &&
                    row &&
                    JSON.stringify(row) !== '{}' &&
                    row[item.fieldEname] &&
                    row[item.fieldEname] !== '-'
                  "
                >
                  {{ getRealDataFileName(row, item) }}
                </span>
              </template>
            </el-table-column>
          </template>

          <!-- 审核状态 -->
          <el-table-column
            width="100"
            v-if="functionMap.examine.show"
            align="center"
            prop="prop"
            label="审核状态"
          >
            <template #default="{ row }">
              <span class="text-red font-bold" v-if="row.EXMINE_STATUS === '已驳回'">已驳回</span>
              <span class="text-green font-bold" v-else-if="row.EXMINE_STATUS === '已完成'">
                审核完成
              </span>
              <span v-else>
                {{ getExmineShow(row) ? '审核中' : '-' }}
              </span>
            </template>
          </el-table-column>

          <!-- 流转状态 -->
          <el-table-column width="100" v-if="isShowTransfer" align="center" prop="prop" label="流转状态">
            <template #default="{ row }">
              <span class="text-green font-bold" v-if="row.TRANSFER_STATUS === '已流转'">已流转</span>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column
            v-if="handleWidth > 0"
            align="center"
            prop="prop"
            label="操作"
            :width="handleWidth"
            fixed="right"
          >
            <template #default="{ row }">
              <el-button
                :loading="row.loading"
                v-if="functionMap.delete.show"
                @click="removeRow(row)"
                size="small"
                type="danger"
                plain
              >
                删除
              </el-button>
              <el-button
                @click="editRow(row)"
                v-if="functionMap.edit.show"
                size="small"
                type="primary"
                plain
              >
                编辑
              </el-button>
              <el-button
                v-if="functionMap.check.show"
                @click="checkRow(row)"
                size="small"
                type="primary"
                plain
              >
                查看
              </el-button>
              <el-button
                @click="submitAndTransfer(row)"
                :loading="row.loadingSubmit"
                v-if="functionMap.submit.show"
                size="small"
                type="primary"
                plain
              >
                提交
              </el-button>
              <el-button
                @click="openExmineDialog(row)"
                v-if="getExmineShow(row)"
                size="small"
                type="success"
                plain
              >
                审核
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-4 flex items-center">
        <el-pagination
          v-model:current-page="searchInfo.size"
          v-model:page-size="searchInfo.limit"
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          @current-change="handleCurrentChange"
        />

        <div>
          <span class="text-sm text-gray5 mx-3">每页</span>
          <el-input-number
            v-model="searchInfo.limit"
            :min="1"
            :max="1000"
            controls-position="right"
          ></el-input-number>
          <span class="text-sm text-gray5 mx-3">条</span>
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <el-dialog title="导入字段" width="500" v-model="showDialog" :close-on-click-modal="false">
      <div class="p-10">
        <el-form class="flex-center flex-col" label-width="0" label-position="left">
          <el-form-item class="mb-10">
            <el-button type="primary" @click="downloadTemplate">
              <i-ep-download class="mr-1" />
              下载模板
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-upload
              v-model:file-list="uploadFile"
              ref="upload"
              class="upload-demo"
              action="#"
              :limit="1"
              accept=".xls,.xlsx"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">
                  <i-ep-document class="mr-1" />
                  选择文件
                </el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button
          :loading="loadingBtn"
          :disabled="uploadFile.length === 0"
          type="primary"
          @click="importFile"
        >
          确定导入
        </el-button>
      </div>
    </el-dialog>

    <!-- 列表自定义 -->
    <el-dialog title="列表自定义" width="600" v-model="showDialogCustom" :close-on-click-modal="false">
      <div class="table-content">
        <el-table border :data="fieldListSort" style="width: 100%; transition: all 0.1s">
          <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
          <el-table-column align="center" prop="fieldName" label="字段名称"></el-table-column>
          <el-table-column align="center" prop="prop" label="表头展示" width="120">
            <template #default="{ row }">
              <el-checkbox v-model="row.show"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="prop" label="移动" width="150">
            <template #default="{ row }">
              <el-button
                @click="moveTableHead(row, 'top')"
                v-if="row.index != 0"
                size="small"
                type="primary"
                plain
              >
                上移
              </el-button>
              <el-button
                @click="moveTableHead(row, 'bottom')"
                v-if="row.index != fieldList.length - 1"
                size="small"
                type="primary"
                plain
              >
                下移
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="flex justify-end mt-5">
        <el-button @click="showDialogCustom = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="saveSort">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 新增 -->
    <el-dialog
      :title="mode === 'check' ? '查看' : mode === 'add' ? '新增' : '编辑'"
      width="900"
      v-model="showDialogAdd"
      :close-on-click-modal="false"
    >
      <div class="p-5 pt-0">
        <el-form
          :disabled="mode === 'check'"
          ref="formRef"
          :rules="rules"
          :model="ruleForm"
          inline
          label-width="100px"
          label-position="left"
        >
          <el-form-item
            v-for="item in fieldList"
            :key="item.id"
            class="w-47%"
            :label="item.fieldName"
            :prop="item.fieldEname"
          >
            <!-- 字段类型：输入框 -->
            <div v-if="item.fieldType === '输入框'" class="w-full">
              <el-input
                :disabled="judgeEditDisabled(item)"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请输入"
              ></el-input>
            </div>
            <!-- 字段类型：日期选择 -->
            <div v-else-if="item.fieldType === '日期选择'" class="w-full">
              <el-date-picker
                :disabled="judgeEditDisabled(item)"
                clearable
                v-model="ruleForm[item.fieldEname]"
                type="datetime"
                placeholder="请选择"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
            <!-- 字段类型：下拉选择 -->
            <div v-else-if="item.fieldType === '下拉框'" class="w-full">
              <el-tree-select
                filterable
                :data="item.dataArr"
                clearable
                :disabled="judgeEditDisabled(item)"
                :check-strictly="item.notSelect === '可选任意层级' ? true : false"
                :render-after-expand="false"
                class="w-full"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请选择"
                node-key="selectCode"
                :props="{
                  label: 'selectName',
                  children: 'children'
                }"
              />
            </div>
            <!-- 字段类型：单选框 -->
            <div v-else-if="item.fieldType === '单选框'" class="w-full mt--1">
              <el-radio-group :disabled="judgeEditDisabled(item)" v-model="ruleForm[item.fieldEname]">
                <el-radio
                  v-for="item_ in item.dataArr"
                  :key="item_.id"
                  :label="item_.selectCode"
                  size="large"
                >
                  {{ item_.selectName }}
                </el-radio>
              </el-radio-group>
            </div>
            <!-- 字段类型：复选框 -->
            <div v-else-if="item.fieldType === '复选框'" class="w-full">
              <el-checkbox-group :disabled="judgeEditDisabled(item)" v-model="ruleForm[item.fieldEname]">
                <el-checkbox v-for="item_ in item.dataArr" :key="item_.id" :label="item_.selectCode">
                  {{ item_.selectName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- 字段类型：省市区 -->
            <div v-else-if="item.fieldType === '省市区'" class="w-full">
              <el-cascader
                :disabled="judgeEditDisabled(item)"
                class="w-full"
                v-model="ruleForm[item.fieldEname]"
                :options="regionData"
                placeholder="请选择省市区"
                filterable
                clearable
              ></el-cascader>
            </div>
            <!-- 字段类型：文件上传 -->
            <div v-else-if="item.fieldType === '文件上传-最多五个'" class="w-full flex items-center">
              <el-upload
                :auto-upload="false"
                v-model:file-list="ruleForm.fileList"
                class="upload-demo flex items-start flex-col"
                action="#"
                multiple
                :limit="5"
                :disabled="judgeEditDisabled(item)"
              >
                <el-button type="primary" class="mr-3">
                  <i-ep-upload class="mr-1"></i-ep-upload>
                  上传
                </el-button>
                <template #file="{ file, index }">
                  <div class="w-full">
                    <span>{{ file.showFile || file.name }}</span>
                    <i-ep-download
                      @click="downloadFile(file.name)"
                      v-if="mode !== 'add' && file.showFile"
                      class="ml-3 pt-1 cursor-pointer"
                      color="blue"
                    />
                    <i-ep-delete
                      @click="
                        () => {
                          ruleForm.fileList.splice(index, 1);
                        }
                      "
                      v-if="mode !== 'check'"
                      class="ml-3 pt-1 cursor-pointer"
                      color="red"
                    />
                  </div>
                </template>
              </el-upload>
            </div>
            <!-- 字段类型：系统人员单选 -->
            <div v-else-if="item.fieldType === '系统人员单选'" class="w-full">
              <el-select
                :disabled="judgeEditDisabled(item)"
                v-if="userList"
                clearable
                filterable
                class="w-full"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请选择"
              >
                <el-option
                  v-for="item_ in userList"
                  :key="item_.userId"
                  :label="item_.userName"
                  :value="item_.userName"
                ></el-option>
              </el-select>
            </div>
            <!-- 字段类型：系统人员多选 -->
            <div v-else-if="item.fieldType === '系统人员多选'" class="w-full">
              <el-select
                clearable
                multiple
                :disabled="judgeEditDisabled(item)"
                filterable
                collapse-tags
                collapse-tags-tooltip
                class="w-full"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请选择"
              >
                <el-option
                  v-for="item_ in userList"
                  :key="item_.userId"
                  :label="item_.userName"
                  :value="item_.userName"
                ></el-option>
              </el-select>
            </div>
            <!-- 字段类型：数字输入框 -->
            <div v-if="item.fieldType === '数字类型'" class="w-full">
              <el-input-number
                class="w-full"
                :precision="0"
                :disabled="judgeEditDisabled(item)"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请输入"
              ></el-input-number>
            </div>
            <!-- 字段类型：组织名称单选 -->
            <div v-else-if="item.fieldType === '组织名称单选'" class="w-full">
              <el-select
                :disabled="judgeEditDisabled(item)"
                v-if="orgInfo"
                clearable
                filterable
                class="w-full"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请选择"
              >
                <el-option
                  v-for="item_ in orgInfo"
                  :key="item_.orgId"
                  :label="item_.orgName"
                  :value="item_.orgName"
                ></el-option>
              </el-select>
            </div>
            <!-- 字段类型：组织名称多选 -->
            <div v-else-if="item.fieldType === '组织名称多选'" class="w-full">
              <el-select
                :disabled="judgeEditDisabled(item)"
                v-if="orgInfo"
                clearable
                collapse-tags
                collapse-tags-tooltip
                multiple
                filterable
                class="w-full"
                v-model="ruleForm[item.fieldEname]"
                placeholder="请选择"
              >
                <el-option
                  v-for="item_ in orgInfo"
                  :key="item_.orgId"
                  :label="item_.orgName"
                  :value="item_.orgName"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialogAdd = false">{{ mode === 'check' ? '关 闭' : '取 消' }}</el-button>
        <el-button v-if="mode !== 'check'" :loading="loadingBtn" type="primary" @click="submit(formRef)">
          保 存
        </el-button>
      </div>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog title="审核" width="800" v-model="showDialogExamine" :close-on-click-modal="false">
      <div class="p-x5">
        <el-steps
          finish-status="success"
          v-loading="loadingExmine"
          direction="vertical"
          :active="activeExmineIndex"
        >
          <el-step :title="'审核人：' + item.userName" v-for="(item, index) in exmineList">
            <template #description>
              <el-form :disabled="!item.enabled" label-position="left" label-width="100px" class="p-5">
                <el-form-item label="审核状态">
                  <el-radio-group v-model="item.auditStatus">
                    <el-radio label="通过">通过</el-radio>
                    <el-radio label="驳回">驳回</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="审核意见">
                  <el-input v-model="item.auditOpinion" placeholder="请输入审核意见"></el-input>
                </el-form-item>
                <el-form-item label="可选择抄送人">
                  <el-select
                    v-model="item.ccUserIds"
                    class="w-full"
                    clearable
                    multiple
                    placeholder="选择抄送人"
                  >
                    <el-option
                      v-for="item__ in userList"
                      :key="item__.userId"
                      :label="item__.userName"
                      :value="item__.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="审核时间">
                  <span class="text-gray">{{ item.createTime || '暂未审核' }}</span>
                </el-form-item>
              </el-form>
            </template>
            <template v-if="item.auditStatus === '驳回'" #icon>
              <i-ep-CircleCloseFilled size="7" color="red" />
            </template>
            <template v-if="item.auditStatus === '驳回'" #title>
              <span class="text-red">审核人：{{ item.userName }}</span>
            </template>
          </el-step>
        </el-steps>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialogExamine = false">取 消</el-button>
        <el-button
          v-if="exmineList.length > 0"
          :disabled="
            exmineList.length === activeExmineIndex || !exmineList[Number(activeExmineIndex)].enabled
          "
          :loading="loadingBtn"
          type="primary"
          @click="saveExmine"
        >
          保 存
        </el-button>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup lang="ts">
//@ts-nocheck
import { useAppStore } from '@/store/modules/app';
import { useQueryTable } from '@/utils/hooks/useQueryTable';
import axios from 'axios';
import {
  ledgerMenuTableFieldListApi,
  ledgerTableSortFormListApi,
  ledgerAuditRecordFormApi,
  ledgerFieldSelectTabApi,
  ledgerAuditRecordTabApi,
  ledgerMenuTosetTabApi,
  ledgerTableSortTabApi,
  ledgerMenuQueryTabApi,
  ledgerMenuFuncTabApi,
  ledgerMenuTabApi,
  ledgerImportApi,
  ledgerFormApi,
  ledgerRoamApi,
  ledgerTabApi,
  ledgerDelApi,
  uploadApi,
  userListApi,
  getUserInfoApi,
  getRoleRightTreeApi
} from '@/utils/api/createPage';
import { ElLoading, FormInstance } from 'element-plus';
import XyTools from '@/utils/functions/xy-tools';
import { regionData } from 'element-china-area-data';
import config from '@/utils/config';

const $xy = new XyTools();
const formRef = ref<FormInstance>();
const appStore = useAppStore();
const searchParams = $xy.SR();
const showDialog = ref(false);
const showDialogCustom = ref(false);
const showDialogAdd = ref(false);
const showDialogExamine = ref(false);
const mode = ref('add'); // 编辑 新增 查看模式
const functionMap = reactive({
  add: {
    show: false,
    config: {}
  },
  delete: {
    show: false,
    config: {}
  },
  check: {
    show: false,
    config: {}
  },
  edit: {
    show: false,
    config: {}
  },
  import: {
    show: false,
    config: {}
  },
  export: {
    show: false,
    config: {}
  },
  examine: {
    show: false,
    config: {}
  },
  submit: {
    show: false,
    config: {}
  }
}); // 功能
const fieldList = ref([]); // 显示字段列表
const fieldListSort = ref([]); // 显示字段列表
const searchFields = ref([]); // 查询字段列表
const uploadFile = ref([]); // 导入文件
const userList = ref(null); // 用户列表
const handleWidth = ref(0); // 处理宽度
const ruleForm = ref({}); // 表单
const rules = ref({}); // 表单规则
const activeExmineIndex = ref(0); // 审核索引
const exmineList = ref([]); // 审核列表
const loadingExmine = ref(false); // 审核加载状态

let currentPage = null; // 当前菜单信息
let currentTable = null; // 选中的表格
let pageMenuName = ''; // 菜单模块名
let loadingFull = null; // 全部加载状态
let handleAddWidth = 76; // 操作烂宽度
let transferConfig = null; // 流转配置
let userInfo = null; // 用户信息
let orgInfo = null; // 组织信息
let premissionInfo = []; // 角色权限信息

// 初始化
const init = async () => {
  if (searchParams && searchParams.menuName) {
    pageMenuName = decodeURI(searchParams.menuName);

    $xy.log('菜单名称:', pageMenuName);
  }

  if (!pageMenuName) return ElMessage.error('未找到菜单名称');

  searchInfo.paramMap = {};
  searchInfo.limit = 25;

  loadingFull = ElLoading.service({
    lock: true,
    text: '读取菜单信息',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  await Promise.all([queryMenuInfo(), queryUserInfo()]); // 查询菜单信息与用户信息
  await queryCustomConfig(); // 查询自定义字段信息
  await queryTransferConfig(); // 查询流转配置
  await queryFunctionConfig(); // 查询功能配置
  queryOrgInfo(); // 查询组织信息
  queryTableData(); // 查询表格数据
  querySearchConfig(); // 查询搜索配置
};

// 查询用户信息
const queryUserInfo = async () => {
  const res = await getUserInfoApi();

  if (res.status === 200) {
    userInfo = res.data;

    queryPremissionInfo();
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询用户对应的权限信息
const queryPremissionInfo = async () => {
  const res = await getRoleRightTreeApi({ roleId: userInfo.roleId ? userInfo.roleId : '' });

  if (res.status === 200) {
    premissionInfo = $xy.FindTreeChildrenById(res.data, currentPage.id);
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询组织信息
const queryOrgInfo = async () => {
  const res = await axios.get(config.baseUrl + '/cdledger/ledger-menu-do/organList', {
    headers: { token: config.token }
  });

  if (res.data && res.data.status && res.data.status === 200) {
    orgInfo = res.data.data;
  } else {
    ElMessage.error(res.data.status.message);
  }
};

// 查询菜单信息
const queryMenuInfo = async () => {
  const res = await ledgerMenuTabApi({ menuName: pageMenuName });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      currentPage = res.data[0];
    } else {
      ElMessage.error('未查询到菜单对应表');
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询实际数据
const queryRealDataArr = (row) => {
  const obj = fieldList.value.find((item) => item.fieldId === row.fieldId);

  return obj ? obj.dataArr : [];
};

const queryRealDataArrStrict = (row) => {
  const obj = fieldList.value.find((item) => item.fieldId === row.fieldId);

  return obj.notSelect === '可选任意层级' ? true : false;
};

// 获取合计值
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;

  const sums: (string | VNode)[] = [];

  columns.forEach((column, index) => {
    if (fieldList.value[index - 1]?.fieldType === '数字类型') {
      const values = data.map((item) => Number(item[column.property]));

      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0)}`;
      } else {
        sums[index] = 'N/A';
      }
    }

    if (index === 0) {
      sums[index] = h('div', {}, ['总计']);
      return;
    }
  });

  return sums;
};

// 查询自定义字段信息
const queryCustomConfig = async () => {
  loadingFull.text = '查询字段信息';

  const res = await ledgerTableSortTabApi({ menuId: currentPage.id });

  if (res.status === 200) {
    queryFieldList(res.data); // 查询表头字段信息
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询表头字段列表
const queryFieldList = async (customConfig) => {
  const res = await ledgerMenuTableFieldListApi({ id: currentPage.id });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      res.data.forEach((item, index: number) => {
        const __obj = customConfig.find((item_) => item_.fieldEname === item.fieldEname);

        if (__obj) {
          item.show = __obj.headShow === 'true' ? true : false;
          item.index = Number(__obj.sortNum);
        } else {
          item.show = true;
          item.index = index;
        }

        item.fixed = null;

        if (item.fieldType === '单选框' || item.fieldType === '复选框' || item.fieldType === '下拉框') {
          // 这三项查找对应的数据
          item.dataArr = [];
          getFieldData(item);
        } else if (item.fieldType.indexOf('系统人员') > -1) {
          !userList.value && getUserList();
        }

        initSubmitForm(item); // 初始化表单数据
      });

      fieldList.value = res.data;

      fieldList.value.sort((a, b) => a.index - b.index);
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 是否展示流转信息
const isShowTransfer = computed(() => {
  let flag = false;

  if (transferConfig && transferConfig.length > 0) {
    if (transferConfig[0].toType === '不流转') {
      flag = false;
    } else {
      flag = true;
    }
  }

  return flag;
});

// 当前登录人信息
const getUserList = async () => {
  userList.value = [];

  const res = await userListApi();

  if (res.status === 200) {
    userList.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 初始化表单
const initSubmitForm = (row) => {
  if (row.notNull === '必填') {
    rules.value[row.fieldEname] = [{ required: true, message: '必填项', trigger: 'blur' }];
  }
};

// 获取字段的数据
const getFieldData = async (row) => {
  const res = await ledgerFieldSelectTabApi({ page: 1, limit: 9999, fieldId: row.fieldId });

  if (res.status === 200) {
    row.dataArr = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 格式化搜索参数
const formatSearchParams = () => {
  let __search = JSON.parse(JSON.stringify(searchInfo));

  for (let key in __search.paramMap) {
    if (__search.paramMap.hasOwnProperty(key)) {
      const obj = fieldList.value.find((item) => item.fieldEname === key);

      if (obj) {
        if (obj.fieldType === '数字类型') {
          if (__search.paramMap[key].start !== null && __search.paramMap[key].start !== null) {
            __search.paramMap[key] = __search.paramMap[key].start + ',' + __search.paramMap[key].end;
          } else {
            __search.paramMap[key] = '';
          }
        } else if (
          obj.fieldType === '组织名称多选' ||
          obj.fieldType === '系统人员多选' ||
          obj.fieldType === '省市区' ||
          obj.fieldType === '复选框' ||
          obj.fieldType === '日期选择'
        ) {
          if (__search.paramMap[key] && __search.paramMap[key].length > 0) {
            __search.paramMap[key] = __search.paramMap[key].join(',');
          } else {
            __search.paramMap[key] = '';
          }
        }
      }
    }
  }

  return __search;
};

// 查询表格内容数据
const queryTableData = async () => {
  loading.value = true;

  searchInfo.menuId = currentPage.id;

  const __search = formatSearchParams();

  const res = await ledgerTabApi(__search);
  loading.value = false;

  if (res.status === 200) {
    if (!res.data) return;

    res.data.forEach((item) => {
      item.loading = false;
      item.loadingSubmit = false;
    });

    tableData.value = res.data;
    total.value = res.count ? Number(res.count) : 0;
    loadingFull.close();

    setTimeout(() => {
      setTableLock(); // 设置表格列锁定
    });
  } else {
    ElMessage.error(res.msg);
  }
};

// 设置表格列锁定
const setTableLock = () => {
  const TR = document.querySelector('table > thead > tr');
  const THS = TR?.querySelectorAll('th');

  THS?.forEach((item, index) => {
    if (index !== 0 && index !== THS.length - 1) {
      item.style.position = 'relative';

      const div = document.createElement('div');

      div.className = 'column-lock';

      fieldList.value[index - 1].fixed = false;

      div.addEventListener('click', () => {
        if (fieldList.value[index - 1].fixed) {
          fieldList.value[index - 1].fixed = false;
          div.innerHTML =
            '<svg t="1739240553013" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7157" width="200" height="200"><path d="M768.25422 0q48.810328 0 94.061569 18.303873t80.333664 50.33565 56.436941 74.740814 21.354518 91.519364l0 150.49851-123.042701 0 0-122.025819q0-64.063555-36.099305-99.654419t-97.112214-35.590864q-54.911619 0-88.468719 35.590864t-33.5571 99.654419l0 124.059583-128.12711 0 0-152.532274q0-48.810328 19.320755-91.519364t53.386296-74.740814 80.333664-50.33565 101.179742-18.303873zM766.220457 693.513406l0 87.451837 0 47.793446q0 27.455809-9.660377 51.860973t-26.438928 41.692155-39.658391 27.455809-50.33565 10.168818l-514.542205 0q-27.455809 0-49.82721-9.660377t-38.641509-26.438928-24.913605-39.14995-8.643496-47.793446l0-323.368421q0-28.472691 19.829196-47.793446t46.268123-19.320755l629.449851 0q28.472691 0 47.793446 19.320755t19.320755 47.793446l0 179.988083z" p-id="7158" fill="#bfbfbf"></path></svg>';
        } else {
          fieldList.value[index - 1].fixed = true;
          div.innerHTML =
            '<svg t="1739240267565" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6038" width="200" height="200"><path d="M385.150849 385.662338l-128.895105 0 0-150.377622q0-49.102897 19.436563-91.556444t53.706294-74.677323 80.815185-50.637363 101.786214-18.413586q49.102897 0 94.625375 18.413586t80.815185 50.637363 56.263736 74.677323 20.971029 91.556444l0 150.377622-123.78022 0 0-121.734266q0-64.447552-35.804196-99.74026t-97.182817-35.292707q-55.240759 0-88.999001 35.292707t-33.758242 99.74026l0 121.734266zM826.053946 447.040959q27.62038 0 47.568432 19.948052t19.948052 47.568432l0 317.122877q0 27.62038-9.718282 51.66034t-26.597403 41.942058-39.896104 28.131868-50.637363 10.22977l-516.603397 0q-27.62038 0-50.125874-10.22977t-38.361638-27.108891-24.551449-39.384615-8.695305-48.07992l0-324.283716q0-27.62038 19.436563-47.568432t47.056943-19.948052l61.378621 0 128.895105 0 255.744256 0 123.78022 0 61.378621 0z" p-id="6039" fill="#bfbfbf"></path></svg>';
        }
      });

      div.innerHTML =
        '<svg t="1739240553013" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7157" width="200" height="200"><path d="M768.25422 0q48.810328 0 94.061569 18.303873t80.333664 50.33565 56.436941 74.740814 21.354518 91.519364l0 150.49851-123.042701 0 0-122.025819q0-64.063555-36.099305-99.654419t-97.112214-35.590864q-54.911619 0-88.468719 35.590864t-33.5571 99.654419l0 124.059583-128.12711 0 0-152.532274q0-48.810328 19.320755-91.519364t53.386296-74.740814 80.333664-50.33565 101.179742-18.303873zM766.220457 693.513406l0 87.451837 0 47.793446q0 27.455809-9.660377 51.860973t-26.438928 41.692155-39.658391 27.455809-50.33565 10.168818l-514.542205 0q-27.455809 0-49.82721-9.660377t-38.641509-26.438928-24.913605-39.14995-8.643496-47.793446l0-323.368421q0-28.472691 19.829196-47.793446t46.268123-19.320755l629.449851 0q28.472691 0 47.793446 19.320755t19.320755 47.793446l0 179.988083z" p-id="7158" fill="#bfbfbf"></path></svg>';

      item.appendChild(div);
    }
  });
};

// 查询功能配置
const queryFunctionConfig = async () => {
  loadingFull.text = '查询配置项目';

  const res = await ledgerMenuFuncTabApi({ menuId: currentPage.id });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      res.data.forEach((item) => {
        const flag = premissionInfo.find((item__) => item__.label === item.funcName);

        if (!flag) return;

        if (item.funcName === '新增') {
          functionMap.add.show = true;
          functionMap.add.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
        } else if (item.funcName === '导入') {
          functionMap.import.show = true;
          functionMap.import.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
        } else if (item.funcName === '导出') {
          functionMap.export.show = true;
          functionMap.export.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
        } else if (item.funcName === '删除') {
          functionMap.delete.show = true;
          functionMap.delete.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
          handleWidth.value += handleAddWidth -= 3;
        } else if (item.funcName === '编辑') {
          functionMap.edit.show = true;
          functionMap.edit.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
          handleWidth.value += handleAddWidth -= 3;
        } else if (item.funcName === '查看单条') {
          functionMap.check.show = true;
          functionMap.check.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
          handleWidth.value += handleAddWidth -= 3;
        } else if (item.funcName === '审核') {
          functionMap.examine.show = true;
          functionMap.examine.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
          handleWidth.value += handleAddWidth -= 3;
          !userList.value && getUserList();
        } else if (item.funcName === '提交') {
          if (transferConfig.length > 0) {
            if (
              transferConfig[0].toType === '按操作流转' &&
              transferConfig[0].selectHandle === '提交再流转'
            ) {
              functionMap.submit.show = true;
              functionMap.submit.config = item.ruleContent ? JSON.parse(item.ruleContent) : {};
              handleWidth.value += handleAddWidth -= 3;
            }
          }
        }
      });
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询搜索配置
const querySearchConfig = async () => {
  const res = await ledgerMenuQueryTabApi({ menuId: currentPage.id });

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      searchFields.value = res.data;
      resetSearchParams();
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 重新设置搜索参数
const resetSearchParams = () => {
  searchFields.value.forEach((item) => {
    if (item.fieldType === '数字类型') {
      searchInfo.paramMap[item.fieldEname] = {
        start: null,
        end: null
      };
    } else if (
      item.fieldType === '省市区' ||
      item.fieldType === '复选框' ||
      (item.fieldType === '系统人员多选') | (item.fieldType === '组织名称多选') ||
      item.fieldType === '日期选择'
    ) {
      searchInfo.paramMap[item.fieldEname] = [];
    } else {
      searchInfo.paramMap[item.fieldEname] = '';
    }
  });
};

// 查询流转配置
const queryTransferConfig = async () => {
  const res = await ledgerMenuTosetTabApi({ menuId: currentPage.id });

  if (res.status === 200) {
    transferConfig = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 重置表格数据
const resetTableData = () => {
  searchInfo.page = 1;

  resetSearchParams();

  queryTableData();
};

// 获取区域真实数据
const getRealDataArea = (row, field) => {
  let __flagArr = [];
  let __regionArr = [];

  if (field) {
    __flagArr = row[field.fieldEname].split(',');

    let __storage = regionData;

    __flagArr.forEach((item) => {
      const __obj = __storage.find((item_) => item_.value === item);

      __regionArr.push(__obj ? __obj.label : '未知');

      __storage = __obj?.children || [];
    });
  }

  return __regionArr.join('/');
};

// 获取下拉真实数据
const getRealDataSelect = (row, field) => {
  let __str = '-';
  let treeData = field.dataArr ? field.dataArr : [];

  function findTreeData(tree, content) {
    tree.forEach((item) => {
      if (item.selectCode === content) {
        __str = item.selectName;
        return;
      } else {
        item.children && findTreeData(item.children, content);
      }

      return;
    });
  }

  findTreeData(treeData, row[field.fieldEname]);

  return __str;
};

// 获取单选框真实数据
const getRealDataRadio = (row, field) => {
  const __content = row[field.fieldEname];
  const __dataArr = field.dataArr ? field.dataArr : [];

  let __str = __dataArr.find((item) => item.selectCode === __content)?.selectName;

  return __str ? __str : '-';
};

// 获取下拉真实数据
const getRealDataCheck = (row, field) => {
  let strArr = [];

  const __content = row[field.fieldEname].split(',');
  const __dataArr = field.dataArr ? field.dataArr : [];

  if (__content) {
    __content.forEach((item) => {
      const __obj = __dataArr.find((item_) => item_.selectCode === item);

      if (__obj) {
        strArr.push(__obj.selectName);
      }
    });
  }

  return strArr.join(',');
};

// 获取文件真实数据
const getRealDataFileName = (row, field) => {
  const __content = row[field.fieldEname];

  return __content ? __content.split('_')[1] : '';
};

const { tableData, total, loading, searchInfo, loadingBtn, cellStyle, handleCurrentChange } =
  useQueryTable(queryTableData);

// 删除行
const removeRow = (row) => {
  ElMessageBox.confirm('是否确定删除此项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      if (row.LEDGER_CREATE_USER_ID !== userInfo.userId)
        return ElMessage.error('该数据非当前登录人创建，无法删除');

      const __config = functionMap.delete.config;

      if (__config && __config.isDel === '按条件删除') {
        const isExmine = __config.delCondition.includes('审核未通过可删除');
        const isTransfer = __config.delCondition.includes('未经流转可删除');

        if (isExmine && row.EXMINE_STATUS !== '已驳回') {
          if (row.EXMINE_STATUS === '已完成') {
            return ElMessage.error('已完成审核，无法删除');
          } else {
            return ElMessage.error('审核中无法删除');
          }
        }

        if (isTransfer && row.TRANSFER_STATUS === '已流转') {
          return ElMessage.error('已流转的数据无法删除');
        }
      }

      row.loading = true;
      const res = await ledgerDelApi({ id: row.ID, menuId: currentPage.id });
      row.loading = false;

      if (res.status === 200) {
        ElMessage.success('已删除');
        queryTableData();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 查看数据
const checkRow = (row) => {
  mode.value = 'check';
  resetFormData(row);
};

// 编辑数据
const editRow = (row) => {
  mode.value = 'edit';
  resetFormData(row);
};

// 重置赋值表单数据
const resetFormData = (row) => {
  loadingBtn.value = false;
  ruleForm.value = JSON.parse(JSON.stringify(row));
  ruleForm.value['fileList'] = [];

  fieldList.value.forEach((item) => {
    if (
      item.fieldType === '省市区' ||
      item.fieldType === '复选框' ||
      item.fieldType === '系统人员多选' ||
      item.fieldType === '组织名称多选'
    ) {
      if (ruleForm.value[item.fieldEname] === '-') {
        // 格式化了所有表格的值 空返回的是 '-'
        ruleForm.value[item.fieldEname] = [];
      } else {
        ruleForm.value[item.fieldEname] = ruleForm.value[item.fieldEname].split(',');
      }
    } else if (item.fieldType === '文件上传-最多五个') {
      // 格式化了所有表格的值 空返回的是 '-'
      if (ruleForm.value[item.fieldEname] === '-') return;

      ruleForm.value['fileList'] = ruleForm.value[item.fieldEname].split(',').map((item) => {
        return {
          name: item,
          url: item,
          showFile: item ? item.split('_')[1] : ''
        };
      });
    } else if (item.fieldType === '数字类型') {
      ruleForm.value[item.fieldEname] = Number(ruleForm.value[item.fieldEname]);
    } else {
      if (ruleForm.value[item.fieldEname] === '-') {
        // 格式化了所有表格的值 空返回的是 '-'
        ruleForm.value[item.fieldEname] = '';
      }
    }
  });

  showDialogAdd.value = true;
};

// 导出数据
const exportTable = async () => {
  window.open(config.baseUrl + `/cdledger/ledger-do/ledgerExport?menuId=${currentPage.id}`, '__blank');
};

// 下载模板
const downloadTemplate = () => {
  if (functionMap.import.config && functionMap.import.config.importModelUrl) {
    window.open(
      config.baseUrl +
        '/cdledger/ledger-menu-func-do/download?fileName=' +
        functionMap.import.config.importModelUrl,
      '__blank'
    );
  } else {
    ElMessage.warning('未上传模板文件');
  }
};

// 文件导入
const importFile = async () => {
  loadingBtn.value = true;

  let formdata = new FormData();

  formdata.append('file', uploadFile.value[0].raw);
  formdata.append('menuId', currentPage.id);

  const res = await ledgerImportApi(formdata);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('操作成功');
    queryTableData();
    showDialog.value = false;
  } else {
    ElMessage.error(res.msg);
  }
};

// 自定义字段
const fieldCustom = () => {
  loadingBtn.value = false;
  showDialogCustom.value = true;
  fieldListSort.value = JSON.parse(JSON.stringify(fieldList.value));
};

// 移动表头
const moveTableHead = (row, type: string) => {
  if (type === 'top') {
    const __index = row.index;
    const __index_1 = row.index - 1;

    [fieldListSort.value[__index_1], fieldListSort.value[__index]] = [
      fieldListSort.value[__index],
      fieldListSort.value[__index_1]
    ];

    [fieldListSort.value[__index_1].index, fieldListSort.value[__index].index] = [
      fieldListSort.value[__index].index,
      fieldListSort.value[__index_1].index
    ];
  } else {
    const __index = row.index;
    const __index_1 = row.index + 1;

    [fieldListSort.value[__index], fieldListSort.value[__index_1]] = [
      fieldListSort.value[__index_1],
      fieldListSort.value[__index]
    ];

    [fieldListSort.value[__index].index, fieldListSort.value[__index_1].index] = [
      fieldListSort.value[__index_1].index,
      fieldListSort.value[__index].index
    ];
  }
};

// 保存排序
const saveSort = async () => {
  if (fieldListSort.value.lengtg === 0) {
    return ElMessage.error('字段列表为空');
  }

  loadingBtn.value = true;

  let __submitForm = [];

  fieldListSort.value.forEach((item, index: number) => {
    __submitForm.push({
      fieldEname: item.fieldEname,
      fieldId: item.fieldId,
      fieldName: item.fieldName,
      headShow: item.show,
      menuId: currentPage.id,
      sortNum: index
    });
  });

  const res = await ledgerTableSortFormListApi(__submitForm);

  loadingBtn.value = false;

  if (res.status === 200) {
    showDialogCustom.value = false;
    fieldList.value = JSON.parse(JSON.stringify(fieldListSort.value));
  } else {
    ElMessage.error(res.msg);
  }
};

// 新增表格数据
const addTableData = () => {
  mode.value = 'add';
  loadingBtn.value = false;

  ruleForm.value.ID && Reflect.deleteProperty(ruleForm.value, 'ID');

  fieldList.value.forEach((item) => {
    if (
      item.fieldType === '复选框' ||
      item.fieldType === '系统人员多选' ||
      item.fieldType === '组织名称多选' ||
      item.fieldType === '省市区'
    ) {
      ruleForm.value[item.fieldEname] = [];
    } else if (item.fieldType === '数字类型') {
      ruleForm.value[item.fieldEname] = 0;
      ruleForm.value['fileList'] = [];
    } else {
      ruleForm.value[item.fieldEname] = '';
      ruleForm.value['fileList'] = [];
    }
  });

  showDialogAdd.value = true;
};

// 文件下载
const downloadFile = (fileName: string) => {
  window.open(config.baseUrl + '/cdledger/ledger-do/download?fileName=' + fileName, '__blank');
};

// 判断能否编辑
const judgeEditDisabled = (row) => {
  if (functionMap.edit && functionMap.edit.config && mode.value === 'edit') {
    if (functionMap.edit.config.isEdit === '所有字段可编辑') {
      return false;
    } else if (functionMap.edit.config.isEdit === '指定字段可编辑' && functionMap.edit.config.fieldId) {
      const obj = functionMap.edit.config.fieldId.find((item) => item === row.fieldId);
      return obj ? false : true;
    }
  }
};

// 是否可以展示审核 *** 如果只有审核人能看到审核按钮可使用 getIsUserCanExmine ***
const getExmineShow = (row) => {
  if (!row || JSON.stringify(row) === '{}' || !functionMap.examine.show) return false;

  const exmineConfig = functionMap.examine.config;

  let flag = false;

  if (exmineConfig.conditionList && exmineConfig.conditionList.length > 0) {
    for (let i = 0; i < exmineConfig.conditionList.length; i++) {
      const fieldFlag = judgeFieldVal(exmineConfig.conditionList[i].fieldList, row); // 判断字段列表是否符合条件

      if (fieldFlag) {
        // 当前字段全部符合条件 结束循环
        flag = true;
        row.exmineCondition = exmineConfig.conditionList[i]; // 保存满足的审核条件到当前选中行
        break;
      } else {
        // 当前字段存在不符合条件的项 继续下一个条件判断
        continue;
      }
    }
  }

  return flag;
};

// 获取一条数据中当前登陆人能否审核  *** 如果任何人均可看到审核按钮可使用 getExmineShow ***
const getIsUserCanExmine = (row) => {
  const exmineConfig = functionMap.examine.config;
  const userId = userInfo.userId; // 当前登录人的 id

  let flag = false;

  if (exmineConfig.conditionList && exmineConfig.conditionList.length > 0) {
    for (let i = 0; i < exmineConfig.conditionList.length; i++) {
      const exmineUser = exmineConfig.conditionList[i].examPerson.find((item) => item.userId === userId);

      if (exmineUser) {
        // 当前审核条件需要登录人审核

        const fieldFlag = judgeFieldVal(exmineConfig.conditionList[i].fieldList, row); // 判断字段列表是否符合条件

        if (fieldFlag) {
          // 当前字段全部符合条件 结束循环
          flag = true;
          row.exmineCondition = exmineConfig.conditionList[i]; // 保存满足的审核条件到当前选中行
          break;
        } else {
          // 当前字段存在不符合条件的项 继续下一个条件判断
          continue;
        }
      }
    }
  }

  return flag;
};

// 判断字段条件
const judgeFieldVal = (list, row) => {
  let flag = false;

  for (let i = 0; i < list.length; i++) {
    const conditionValue = Number(list[i].value); // 字段需要满足的值
    const __isNaN = isNaN(conditionValue); // 是否是数字值
    const __field = fieldList.value.find((item) => item.fieldId === list[i].fieldId);
    const rowFieldValue = getRealRowFieldValue(__field, row); // 待比较是否满足条件的表格值
    const condition = list[i].condition; // 条件

    if (condition === '值大于' || condition === '值小于') {
      if (__isNaN) {
        flag = false;
        break;
      }
    }

    if (condition === '值大于') {
      const rowValueNumber = isNaN(Number(rowFieldValue)) ? undefined : Number(rowFieldValue);

      if (rowValueNumber && rowValueNumber > conditionValue) {
        flag = true;
      } else {
        flag = false;
        break;
      }
    } else if (condition === '值小于') {
      const rowValueNumber = isNaN(Number(rowFieldValue)) ? undefined : Number(rowFieldValue);

      if (rowValueNumber && rowValueNumber < conditionValue) {
        flag = true;
      } else {
        flag = false;
        break;
      }
    } else if (condition === '值等于') {
      if (rowFieldValue && rowFieldValue === list[i].value) {
        flag = true;
      } else {
        flag = false;
        break;
      }
    } else if (condition === '值为空') {
      if (rowFieldValue === '-') {
        flag = true;
      } else {
        flag = false;
        break;
      }
    } else if (condition === '值不为空') {
      if (rowFieldValue !== '-') {
        flag = true;
      } else {
        flag = false;
        break;
      }
    }
  }

  return flag;
};

// 获取真实列数据 制作了下拉和单选框的判断
const getRealRowFieldValue = (field, row) => {
  let realVal = '';

  const dataArr = queryRealDataArr(field);

  if (field.fieldType === '下拉框') {
    realVal = getRealDataSelect(row, field);
  } else if (field.fieldType === '单选框') {
    realVal = dataArr.find((item) => item.selectCode === row[field.fieldEname]);
  } else {
    realVal = row[field.fieldEname];
  }

  return realVal;
};

// 打开审核弹窗
const openExmineDialog = async (row) => {
  showDialogExamine.value = true;
  activeExmineIndex.value = 0;
  currentTable = row;
  loadingBtn.value = false;
  await resetExmineInfo(row);
};

// 提交并流转
const submitAndTransfer = (row) => {
  ElMessageBox.confirm('是否确定提交并流转到其他模块?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      row.loadingSubmit = true;

      const res = await ledgerRoamApi({
        menuId: currentPage.id,
        paramMap: row
      });

      row.loadingSubmit = false;

      if (res.status === 200) {
        ElMessage.success('已提交');
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 重置审核信息
const resetExmineInfo = async () => {
  loadingExmine.value = true;
  const res = await ledgerAuditRecordTabApi({ dataId: currentTable.ID });
  loadingExmine.value = false;

  if (res.status === 200) {
    if (currentTable.exmineCondition && currentTable.exmineCondition.examPerson && userInfo) {
      exmineList.value = currentTable.exmineCondition.examPerson.map((item, index) => {
        return {
          userId: item.userId,
          userName:
            userList.value.find((item__) => item__.userId === item.userId)?.userName || '未设置审核人',
          auditOpinion: '',
          auditStatus: '',
          ccUserIds: [],
          ccUserNames: '',
          menuId: currentPage.id,
          sortNum: index,
          dataId: currentTable.ID,
          createTime: '',
          enabled: false
        };
      });
    }

    if (res.data) {
      if (res.data.length > 0) {
        res.data.forEach((item) => {
          let __index = exmineList.value.findIndex((item__) => item__.userId === item.userId);

          if (__index !== null && __index !== undefined) {
            exmineList.value[__index].auditOpinion = item.auditOpinion;
            exmineList.value[__index].auditStatus = item.auditStatus;
            exmineList.value[__index].ccUserIds = item.ccUserIds.split(',');
            exmineList.value[__index].ccUserNames = item.ccUserNames;
            exmineList.value[__index].createTime = item.createTime;
          }
        });

        activeExmineIndex.value = res.data.length;
      }

      const nowUserExmineIndex = currentTable.exmineCondition.examPerson.findIndex(
        (item) => item.userId === userInfo.userId
      ); // 当前审核人在审核流程中的索引
      const hasExminedLength = res.data.length; // 已审核的流程长度
      const exmineLength = currentTable.exmineCondition.examPerson.length; // 需要审核的流程长度

      if (nowUserExmineIndex > hasExminedLength - 1) {
        // 当前登录人还没有审核
        if (nowUserExmineIndex === hasExminedLength) {
          // 应该审核的位置刚好是当前登录人所在索引

          if (res.data.length > 0 && res.data[res.data.length - 1].auditStatus === '驳回') {
            exmineList.value[nowUserExmineIndex].enabled = false;
            ElMessage.warning('本条流程已被驳回');
          } else {
            exmineList.value[nowUserExmineIndex].enabled = true;
          }
        } else {
          ElMessage.warning('上一步审核尚未完成');
        }
      } else {
        if (nowUserExmineIndex >= 0) {
          ElMessage.success('您已完成本条数据的审核');
        }
      }
    } else {
      ElMessage.error('未查询到当前数据已审核的流程信息');
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 对表单数据进行格式化
const formatForm = async () => {
  let __map = {
    ID: ruleForm.value.ID ? ruleForm.value.ID : $xy.RI(),
    LEDGER_CREATE_USER_ID: ruleForm.value.LEDGER_CREATE_USER_ID
      ? ruleForm.value.LEDGER_CREATE_USER_ID
      : userInfo.userId
  };

  for (let i = 0; i < fieldList.value.length; i++) {
    if (
      fieldList.value[i].fieldType === '复选框' ||
      fieldList.value[i].fieldType === '省市区' ||
      fieldList.value[i].fieldType === '系统人员多选' ||
      fieldList.value[i].fieldType === '组织名称多选'
    ) {
      __map[fieldList.value[i].fieldEname] = ruleForm.value[fieldList.value[i].fieldEname].join(',');
    } else if (fieldList.value[i].fieldType === '文件上传-最多五个') {
      let __str = '';

      const __arr = ruleForm.value['fileList'].filter((item) => item.url);
      const __arrFile = ruleForm.value['fileList'].filter((item) => item.raw);

      if (__arr && __arr.length > 0) {
        __str = __arr.map((item) => item.url).join(',');
      }

      if (__arrFile && __arrFile.length > 0) {
        const formData = new FormData();

        __arrFile.forEach((item) => {
          formData.append('file', item.raw);
        });

        const res = await uploadApi(formData);

        if (res.status === 200) {
          __str = __str ? __str + ',' + res.fileName : res.fileName;
        } else {
          ElMessage.error(res.msg);
        }
      }

      __map[fieldList.value[i].fieldEname] = __str;
    } else {
      __map[fieldList.value[i].fieldEname] = ruleForm.value[fieldList.value[i].fieldEname];
    }
  }

  return __map;
};

// 提交表单
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (!userInfo && mode.value === 'add') ElMessage.error('未获取到用户信息');
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loadingBtn.value = true;

      const __map = await formatForm();

      const __form = {
        menuId: currentPage.id,
        paramMap: __map
      };

      const res = await ledgerFormApi(__form);

      loadingBtn.value = false;

      if (res.status === 200) {
        ElMessage.success('操作成功');
        showDialogAdd.value = false;
        resetTableData();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 保存审核条件
const saveExmine = async () => {
  loadingBtn.value = true;

  const activeExmineItem = exmineList.value[activeExmineIndex.value];

  if (!activeExmineItem || !activeExmineItem.auditStatus) {
    return ElMessage.error('未选择通过审核');
  }

  let userNames = [];

  userList.value.forEach((item) => {
    const __obj = activeExmineItem.ccUserIds.find((item__) => item__ === item.userId);

    if (__obj) {
      userNames.push(item.userName);
    }
  });

  let lastUserId = null;

  if (
    exmineList.value &&
    exmineList.value.length > 0 &&
    exmineList.value[exmineList.value.length - 1].userId === activeExmineItem.userId
  ) {
    lastUserId = userInfo.userId;
  }

  const __form = {
    auditOpinion: activeExmineItem.auditOpinion,
    auditStatus: activeExmineItem.auditStatus,
    ccUserIds: activeExmineItem.ccUserIds.join(','),
    ccUserNames: userNames.join(','),
    dataId: activeExmineItem.dataId,
    menuId: activeExmineItem.menuId,
    sortNum: activeExmineItem.sortNum,
    userId: activeExmineItem.userId,
    userName: activeExmineItem.userName,
    lastUserId
  };

  const res = await ledgerAuditRecordFormApi(__form);

  loadingBtn.value = false;

  if (res.status === 200) {
    resetExmineInfo();
  } else {
    ElMessage.error(res.msg);
  }
};

init();
</script>

<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item:nth-child(even)) {
  margin-right: 0;
}

:deep(.el-form--inline .el-form-item) {
  vertical-align: inherit;
}

:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-step:last-of-type .el-step__description) {
  padding-right: 10%;
}

:deep(.number-type .el-input-number) {
  width: 90px;
}

.search-list {
  display: flex;
  align-items: center;

  & > span {
    white-space: nowrap;
  }
}

:deep(.column-lock) {
  position: absolute;
  right: 2px;
  top: 2px;
  font-size: 12px;
  width: 12px;
  height: 12px;
  cursor: pointer;

  svg {
    width: 100%;
    height: 100%;
  }

  svg:hover {
    fill: white;
  }
}
</style>
